package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook 地址数据
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0); // 新增不设置默认地址
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询地址列表
     *
     * @return 地址列表
     */
    @Override
    public List<AddressBook> getAddressBookList() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.selectList(addressBook);
    }

    /**
     * 根据id查询地址
     *
     * @param id 地址id
     * @return 地址数据
     */
    @Override
    public AddressBook getAddressBook(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setId(id);
        return addressBookMapper.selectById(addressBook);
    }

    /**
     * 更新地址
     *
     * @param addressBook 地址数据
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    /**
     * 更新默认地址
     *
     * @param addressBook 地址数据
     */
    @Override
    public void updateDefaultAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        // 首先根据用户id更新所有默认地址为0
        addressBook.setIsDefault(0);
        addressBookMapper.updateDefaultByUserId(addressBook);
        // 然后再更新指定默认地址为1
        addressBook.setIsDefault(1); // 更新默认地址
        addressBookMapper.update(addressBook);
    }

    /**
     * 查询默认地址
     */
    @Override
    public List<AddressBook> getDefaultAddressBook() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1); // 默认地址
        return addressBookMapper.selectList(addressBook);
    }

    /**
     * 删除地址
     *
     * @param id 地址id
     */
    @Override
    public void deleteAddressBook(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setId(id);
        addressBookMapper.deleteById(addressBook);
    }
}
